package com.mantru.iotpot.dishes

import android.annotation.SuppressLint
import android.os.Bundle
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.distinctUntilChanged
import androidx.recyclerview.widget.StaggeredGridLayoutManager
import com.mantru.iotpot.Adapter.DishesTimePageAdapter
import com.mantru.iotpot.R
import com.mantru.iotpot.databinding.ActivityDishesTimePageBinding

class DishesTimePageActivity : AppCompatActivity() {
    val viewModel by viewModels<DishesTimePageViewModel>()
    private lateinit var binding: ActivityDishesTimePageBinding

    //adapter属于UI层，负责交互，留在Activity
    private var dishesTimePageAdapter: DishesTimePageAdapter? = null

    @SuppressLint("SetTextI18n")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = DataBindingUtil.setContentView(this, R.layout.activity_dishes_time_page)
        binding.viewModel = viewModel // 绑定viewModel
        binding.lifecycleOwner = this // 允许 LiveData 自动更新 UI

        //初始化recyclerview
        setRecyclerView()
        //设置控件交互事件
        setContentAction()
        //观察者模式，观察dishesList变化，更新adapter数据
        setupObservers()
        //获取intent得到的数据
        getIntentValue()
        //设置recyclerview数据
        viewModel.updateDishesList()
    }

    //初始化recyclerview
    private fun setRecyclerView() {
        dishesTimePageAdapter = DishesTimePageAdapter(this, R.layout.adapter_dishes_time_page, viewModel.dishesCreateList.value ?: mutableListOf())
        binding.dishesTimeBottomRecyclerview.apply {
            layoutManager = StaggeredGridLayoutManager(1, StaggeredGridLayoutManager.VERTICAL)
            adapter = dishesTimePageAdapter
        }
    }

    //设置控件交互事件
    @SuppressLint("NotifyDataSetChanged")
    private fun setContentAction() {
        //关闭按钮
        binding.dishesTimeBack.setOnClickListener {
            finish()
        }
    }

    //观察者模式，观察dishesList变化，更新adapter数据
    private fun setupObservers() {
        viewModel.dishesCreateList
            .distinctUntilChanged() // 过滤相同数据
            .observe(this) { list ->
                list?.let {
                    dishesTimePageAdapter?.updateData(it)
                }
            }
    }

    //获取intent得到的数据
    private fun getIntentValue(){
        val vegetableName = intent.getStringExtra("name")
        vegetableName?.let {
            viewModel.vegetableName.set(it)
        }
        val spec = intent.getStringExtra("spec")
        spec?.let {
            viewModel.spec.set(it)
        }
        val specDataJson = intent.getStringExtra("specDataJson")
        specDataJson?.let {
            viewModel.setValue(it)
        }
    }
}